import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { Table, Pagination, Message, Dialog, Button, Balloon, Loading, Grid, Form, Icon } from '@alifd/next';
import IceContainer from '@icedesign/container';
import IconSvg from '#/components/IconSvg';
import TableFilter from './TableFilter';
import EditForm from './EditForm';
import BindMetric from '../BindMetric';
import '#/scss/Global.scss';
import { ApiOfMetricGroupPage, ApiOfMetricGroupEnable, ApiOfMetricGroupDisable, ApiOfMetricGroupDelete, ApiOfMetricGroupExport } from '#/utils/coreApiDefine'
import SearchTableWrapper from '#/hoc/SearchTableWrapper'
import { inject } from 'mobx-react';
const { Row, Col } = Grid;

@inject('dictstore')
@SearchTableWrapper(ApiOfMetricGroupPage)
export default class SearchTable extends Component {
  static displayName = 'SearchTable';

  static propTypes = {};

  static defaultProps = {};

  constructor() {
    super();
    this.state = {
      loading: false,
      detailDialogVisible: false,
      bindDialogVisible: false,
      editInstance: {},
      rowSelection: {
        onChange: this.onRowSelectChange.bind(this),
        selectedRowKeys: [],
        selectedRows: [],
        mode: 'multiple',
      },
    };
  }

  renderConfigDesc = (value, index, item) => {
    let that = this;
    if (!item.config) {
      return (
        <div></div>
      );
    } else {
      let config = JSON.parse(item.config);
      return (
        <div>
          {Object.keys(config).map(function (k) {
            return (
              <dl style={that.props.styles.horizontal.dl} key={k}>
                <dt style={that.props.styles.horizontal.dt}>{k}:</dt>
                <dd style={that.props.styles.horizontal.dd}>{config[k]}</dd>
              </dl>
            );
          })}
        </div>
      );
    }
  }

  renderUsageType = (value, index, item) => {
    let usageTypeItem = this.props.dictstore.MetricUsageTypeDS.find(item => item.value === value)
    return (
      <div>{usageTypeItem.label}</div>
    );
  }

  renderProtocol = (value, index, item) => {
    let protocolItem = this.props.dictstore.ProtocolDS.find(item => item.value === value)
    return (
      <div>{protocolItem.label}</div>
    );
  }

  onDeleteConfirmOk = item => {
    return ApiOfMetricGroupDelete(item.code)
  }

  // 渲染操作按钮示例
  renderOper = (value, index, item) => {
    let that = this;
    const linkProps = {
      to: "/manage/metricgroup/" + item.code + "/bindmetrics"
    };

    const edit = <Button title="编辑" onClick={() => this.onOpenDetailDialog(item)} type="primary" text>
          <IconSvg iconClass="#icon-bianji" style={{ width: '1.2em', height: '1.2em'}} />
        </Button>

    const remove = <Button title="删除" onClick={() => this.props.deleteConfirm(item, this.onDeleteConfirmOk.bind(this))} type="primary" text style={{marginLeft: '5px'}}>
          <IconSvg iconClass="#icon-shanchu" style={{ width: '1.2em', height: '1.2em'}} />
        </Button>

    const metric = <Link title="指标" {...linkProps} style={{ marginLeft: '3px' }}>
          <IconSvg iconClass="#icon-fenzuguanli" style={{ width: '1.2em', height: '1.2em' }} />
        </Link>

    return (
      <div>
        {edit}
        {remove}
        {metric}
      </div>
    );
  }

  onToggleStatusConfirm = (item) => {
    let that = this;
    let Api = item.disabled ? ApiOfMetricGroupEnable : ApiOfMetricGroupDisable
    Dialog.confirm({
      title: '',
      content: '确认要' + (item.disabled ? '开启' : '禁用') + '吗?',
      onOk: () => {
        Api(item.code).then(response => {
          that.props.fetch();
          Message.success('操作成功!');
        }).catch(function (error) {
          console.log(error);
        });
      }
    });
  }

  onOpenDetailDialog = (item) => {
    this.setState({
      detailDialogVisible: true,
      editInstance: item ? item : {}
    });
  }

  onCloseDetailDialog = reason => {
    this.setState({
      detailDialogVisible: false
    });
    if (reason == 'success') {
      Message.success('操作成功!');
      this.props.fetch();
    }
  }

  onOpenBindDialog = item => {
    this.setState({
      bindDialogVisible: true,
      editInstance: item
    });
  }

  onCloseBindDialog = reason => {
    this.setState({
      bindDialogVisible: false
    });
    if (reason == 'success') {
      Message.success('操作成功!');
      this.props.fetch();
    }
  }

  onRowSelectChange(ids, records) {
    const { rowSelection } = this.state;
    rowSelection.selectedRowKeys = ids;
    rowSelection.selectedRows = [...rowSelection.selectedRows, ...records];
    this.setState({ rowSelection });
  }

  onSelectConfirm() {
    let possibleRows = this.state.rowSelection.selectedRows,
      selectedRowKeys = this.state.rowSelection.selectedRowKeys;
    let selectedRows = possibleRows.filter(row => selectedRowKeys.findIndex(key => key == row.id) != -1);
    this.props.onSelect(selectedRows)
  }
  exportData() {
    var that = this;
    var serarch = that.props.search;
    var url = ApiOfMetricGroupExport + '?';
    Object.keys(serarch).forEach(key => {
      if (serarch[key] != null) {
        url = url + key + '=' + serarch[key] + '&';
      }
    });
    fetch(url).then(res => res.blob().then(blob => {
      let a = document.createElement('a');
      let url = window.URL.createObjectURL(blob);
      let filename = res.headers.get('Content-disposition');
      if (filename) {
        filename = decodeURI(filename.split('=')[1]); //提取文件名
        a.href = url;
        a.download = filename; //给下载下来的文件起个名字
        a.click();
        window.URL.revokeObjectURL(url);
        a = null;
      }
    }));
  }
  render() {
    const { instances } = this.props.bindingData;
    let DisplayTable, ActionBar;
    if (this.props.forSelectUsage === true) {
      DisplayTable =
        <div>
          <Table
            dataSource={instances.data}
            loading={this.props.loading}
            hasBorder={false}
            style={{ padding: '0 20px 20px' }}
            onSort={this.props.handleSort}
            rowSelection={this.state.rowSelection}
          >
            <Table.Column width={200} title="名称" dataIndex="name" sortable={true} />
            <Table.Column width={180} title="编码" dataIndex="code" />
            <Table.Column width={120} title="协议" dataIndex="protocol" cell={this.renderProtocol} sortable={true} />
            <Table.Column width={120} title="用途" dataIndex="usageType" cell={this.renderUsageType} sortable={true} />
            {/*<Table.Column width={100} title="采集周期 " dataIndex="executionCycle" sortable={true} />*/}
            <Table.Column width={180}
              title="扩展配置"
              dataIndex="config"
              cell={this.renderConfigDesc}
            />
          </Table>
        </div>
      ActionBar =
        <Button onClick={this.onSelectConfirm.bind(this)} disabled={this.state.rowSelection.selectedRowKeys.length == 0} size="small" type="secondary">
          <Icon type="select" />选好了
        </Button>
    } else {
      DisplayTable =
        <div>
          <Table
            dataSource={instances.data}
            loading={this.props.loading}
            hasBorder={false}
            style={{ padding: '0 20px 20px' }}
            onSort={this.props.handleSort}
          >
            <Table.Column width={200} title="名称" dataIndex="name" sortable={true} />
            <Table.Column width={180} title="编码" dataIndex="code" />
            <Table.Column width={120} title="协议" dataIndex="protocol" cell={this.renderProtocol} sortable={true} />
            <Table.Column width={120} title="用途" dataIndex="usageType" cell={this.renderUsageType} sortable={true} />
            {/*<Table.Column width={100} title="采集周期 " dataIndex="executionCycle" sortable={true} />*/}
            <Table.Column width={140}
              title="扩展配置"
              dataIndex="config"
              cell={this.renderConfigDesc}
            />
            <Table.Column
              width={100}
              title="操作"
              cell={this.renderOper}
            />
          </Table>
        </div>
      ActionBar =
        <div>
          <div style={styles.formItem}>
            <div>
              <Button onClick={this.exportData.bind(this)} type="secondary" size="small"><Icon type="download" />导出数据</Button>
            </div>
            <div>
              <Button onClick={() => this.onOpenDetailDialog()} size="small" type="secondary" style={{ 'marginLeft': '10px' }}><Icon type="add" />新建</Button>
            </div>

          </div>
          {/* <div style={styles.formItem}>
            <form method="get" action={ApiOfMetricGroupExport}>
              <button className="next-btn next-small next-btn-secondary" style={{ 'marginLeft': '10px' }}>导出</button>
            </form>
          </div> */}
        </div>

    }
    return (
      <IceContainer style={this.props.styles.container}>
        <Loading visible={this.state.loading} fullScreen shape="fusion-reactor">
          <TableFilter
            filter={this.props.filter}
            forSelectUsage={this.props.forSelectUsage}
            match={this.props.match}
          />
          <Row wrap gutter="20" style={styles.formRow}>
            <Col l="8">
              {ActionBar}
            </Col>
            <Col l="16">
              <Pagination
                style={{ 'marginBottom': '10px', ...this.props.styles.pagination }}
                shape="arrow-only"
                pageSizeSelector="filter"
                current={this.props.page}
                total={instances.pageable.totalElements}
                totalRender={total => `总数: ${total}`}
                pageSize={instances.pageable.size}
                onChange={this.props.handlePaginationChange}
                onPageSizeChange={this.props.handlePageSizeChange}
              />
            </Col>
          </Row>
          {DisplayTable}
          <Pagination
            style={this.props.styles.pagination}
            shape="arrow-only"
            pageSizeSelector="filter"
            current={this.props.page}
            total={instances.pageable.totalElements}
            totalRender={total => `总数: ${total}`}
            pageSize={instances.pageable.size}
            onChange={this.props.handlePaginationChange}
            onPageSizeChange={this.props.handlePageSizeChange}
          />
        </Loading>
        <Dialog
          style={{ width: '50%' }}
          title="修改指标组信息"
          visible={this.state.detailDialogVisible}
          footer={false}
          onClose={this.onCloseDetailDialog}>
          <EditForm formData={this.state.editInstance} submitCallback={this.onCloseDetailDialog} />
        </Dialog>

        <Dialog
          className="dialog-with-table"
          style={{ width: '80%' }}
          title="添加指标"
          visible={this.state.bindDialogVisible}
          footer={false}
          shouldUpdatePosition={true}
          onClose={this.onCloseBindDialog}>
          <BindMetric code={this.state.editInstance.code} match={this.props.match} submitCallback={this.onCloseBindDialog} />
        </Dialog>
      </IceContainer>
    );
  }
}

const styles = {
  formRow: {
    padding: '10px 20px',
  },
  formItem: {
    display: 'flex',
    alignItems: 'center',
    margin: '10px 0',
  },
};
